package com.roadmap.biz.search;

import java.util.List;

import com.roadmap.biz.common.RdcQueryConst;
import com.roadmap.common.BaseConst;
import com.roadmap.exception.ServerException;
import com.roadmap.repo.db.DatabaseUtility;
import com.roadmap.repo.db.IDatabaseUtility;

public class FriendSearchEngine implements IFriendSearchEngine {
	private final IDatabaseUtility _dataUtil = new DatabaseUtility();
	private final String currentUser;
	
	public FriendSearchEngine(String currentUser) {
		this.currentUser = currentUser;
	}

	public List retrieveFriends(String username, char sex)
			throws ServerException {
		if (username == null) {
			return null;
		}

		String hql = null;
		Object[] params = null;
		if (isSearchingAllSexes(sex)) {
			hql = RdcQueryConst.HQL_USERS_BY_NAME;
			params = new Object[] { username, this.currentUser };
		}
		else {
			hql = RdcQueryConst.HQL_USERS_BY_NAME_SEX;
			params = new Object[] { username, sex, this.currentUser };
		}

		return _dataUtil.executeHQLQuery(hql, params);
	}

	private boolean isSearchingAllSexes(int sex) {
		return sex != BaseConst.ASPIRANT_SEX_MALE
				&& sex != BaseConst.ASPIRANT_SEX_FEMALE;
	}

	public List retrieveFriends(String mail)
			throws ServerException {
		if (mail == null) {
			return null;
		}

		Object[] params = { mail, this.currentUser };
		return _dataUtil.executeHQLQuery(RdcQueryConst.HQL_USER_BY_MAIL, params);
	}

}
